package com.suray.wcs.service.wmsconnect;

import com.alibaba.fastjson.JSON;
import com.suray.commin.annotation.Log;
import com.suray.commin.core.utils.SpringContextHolder;
import com.suray.commin.enmus.BusinessStatus;
import com.suray.wcs.service.config.properties.WcsProperties;
import com.suray.commin.annotation.InterfaceLog;
import com.suray.wcs.service.core.util.HttpClientSpring;
import com.suray.wcs.service.enums.*;
import com.suray.wcs.service.init.SystemInit;
import com.suray.wcs.service.manager.AsyncManager;
import com.suray.wcs.service.manager.factory.AsyncFactory;
import com.suray.wcs.service.system.entity.InterfaceLogDB;
import com.suray.wcs.service.system.entity.TaskDB;
import com.suray.wcs.service.system.entity.TaskDetailDB;
import com.suray.wcs.service.system.service.impl.*;
import com.suray.wcs.service.util.WcsUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

/**
 * @Description:上位系统交互接口类
 * @author: rongbj
 * @date:2019年11月12日 下午3:25:00
 */
@Component
@DependsOn(value = "wmsIpPortUtil")
public class ToWMSImpl implements ToWms {
    private static Logger log = LoggerFactory.getLogger(ToWMSImpl.class);

    private static TaskDBServiceImpl taskDBService = SpringContextHolder.getBean(TaskDBServiceImpl.class);
    private static TaskDetailServiceImpl taskDetailService = SpringContextHolder.getBean(TaskDetailServiceImpl.class);

    private static NodeDBServiceImpl nodeDBService = SpringContextHolder.getBean(NodeDBServiceImpl.class);

    /**
     * 请求WMS申请入库
     *
     * @param taskApply
     * @return
     */
    @Override
    @InterfaceLog(value = "请求WMS申请入库", sender = "WCS", recipient = "WMS")
    public WmsResponses exeTaskApply(TaskApply taskApply) {
        log.info("exeTaskApply taskApply=>{}", JSON.toJSONString(taskApply));
        String result = StringUtils.EMPTY;
        for (int i = 0; i < WcsProperties.ATTEMPT_NUM_3; i++) {
            try {
                result = HttpClientSpring.sendPostRequest(WmsIpPortUtil.getUrl(SystemInit.getUrlByName("exeTaskApply")), JSON.toJSONString(taskApply));
                if (StringUtils.isNotBlank(result)) {
                    break;
                }
            } catch (Exception e) {
                log.info("exeTaskApply 接口异常：{}", e.getMessage(), e);
                sleepSecond(1);
            }
        }
        log.info("exeTaskApply return data:{}", result);
        try {
            if (StringUtils.isBlank(result)) {
                return WmsResponses.returnError("请求未响应");
            }
            WmsResponses wmsResponses = JSON.parseObject(result, WmsResponses.class);
            Integer returnStatus = wmsResponses.getReturnStatus();
            Date msgTime = wmsResponses.getMsgTime();
            String returnInfoFromWms = wmsResponses.getReturnInfo();
            if (returnStatus == WcsProperties.SUCCESS) {
                log.info("任务库口:" + taskApply.getFromPort() + " 托盘码：" + taskApply.getBarCode() + " 的任务申请成功！ 时间-->"
                        + msgTime);
            } else if (returnStatus == WcsProperties.FAIL) {
                log.error("任务库口:" + taskApply.getFromPort() + " 托盘码：" + taskApply.getBarCode() + " 的任务申请失败！原因-->"
                        + returnInfoFromWms + " 时间-->"
                        + msgTime);
            } else {
                log.error("状态码不存在,接收到为！" + returnStatus);
                return WmsResponses.returnError("状态码不存在,接收到为！" + returnStatus);
            }
            return wmsResponses;
        } catch (Exception e) {
            log.error("任务申请接口解析返回值出现异常！{}", e.getMessage(), e);
            return WmsResponses.returnError("任务申请接口解析返回值出现异常");
        }
    }

    /**
     * @return
     * @description:空托盘出库任务申请接口
     * @author caox@suray.cn
     * @date 2020/8/4 9:25
     */
    @Override
    @InterfaceLog(value = "空托盘入库申请", sender = "WCS", recipient = "WMS")
    public WmsResponses emptyPalletApply(PalletRequest palletOutRequest) {
        log.info("emptyPalletApply palletOutRequest=>{}", JSON.toJSONString(palletOutRequest));
        String result = StringUtils.EMPTY;
        for (int i = 0; i < WcsProperties.ATTEMPT_NUM_3; i++) {
            try {
                result = HttpClientSpring.sendPostRequest(WmsIpPortUtil.getUrl(SystemInit.getUrlByName("emptyPalletApply")), JSON.toJSONString(palletOutRequest));
                if (StringUtils.isNotBlank(result)) {
                    break;
                }
            } catch (Exception e) {
                log.info("emptyPalletApply 接口异常：{}", e.getMessage(), e);
                sleepSecond(1);
            }
        }
        log.info("emptyPalletApply return data:{}", result);
        try {
            if (StringUtils.isBlank(result)) {
                return WmsResponses.returnError("请求未响应");
            }
            WmsResponses palletOutResponse = JSON.parseObject(result, WmsResponses.class);
            Integer returnStatus = palletOutResponse.getReturnStatus();
            Date msgTime = palletOutResponse.getMsgTime();
            String returnInfoFromWms = palletOutResponse.getReturnInfo();
            if (returnStatus == WcsProperties.SUCCESS) {
                log.info("任务库口:" + palletOutRequest.getFromPort() + " 申请类型：" + palletOutRequest.getTaskType() + " 的任务申请成功！ 时间-->"
                        + msgTime);
            } else if (returnStatus == WcsProperties.FAIL) {
                log.error("任务库口:" + palletOutRequest.getFromPort() + " 申请类型：" + palletOutRequest.getTaskType() + " 的任务申请失败！原因-->"
                        + returnInfoFromWms + " 时间-->"
                        + msgTime);
                WcsUtil.notification(palletOutRequest.getFromPort() + "申请WMS失败,原因：" + returnInfoFromWms, NotificationTypeEnum.WARN);
            } else {
                log.error("状态码不存在,接收到为！" + returnStatus);
                return WmsResponses.returnError("状态码不存在,接收到为！" + returnStatus);
            }
            return palletOutResponse;
        } catch (Exception e) {
            log.error("空托盘出库任务申请接口解析返回值出现异常！{}", e.getMessage(), e);
            return WmsResponses.returnError("空托盘出库任务申请接口解析返回值出现异常");
        }
    }

    @Override
    public void executionPhase(TaskStatusRtn taskStatusRtn) {
        AsyncManager.me().execute(executionPhaseAsync(taskStatusRtn));
    }

    @Override
    @InterfaceLog(value = "上报WMS设备状态", sender = "WCS", recipient = "WMS")
    public WmsResponses deviceStatus(List<ReturnMsgDevice> deviceErrRtn) {
        log.info("deviceStatus deviceErrRtn=>{}", JSON.toJSONString(deviceErrRtn));
        String result = HttpClientSpring.sendPostRequest(WmsIpPortUtil.getUrl(SystemInit.getUrlByName("deviceStatus")), JSON.toJSONString(deviceErrRtn));
        log.info("deviceStatus return data:{}", result);
        return JSON.parseObject(result, WmsResponses.class);
    }


    private void sleepSecond(int second) {
        try {
            TimeUnit.SECONDS.sleep(second);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 上报WMS执行状态
     *
     * @param taskStatusRtn 操作日志信息
     * @return 任务task
     */
    private TimerTask executionPhaseAsync(final TaskStatusRtn taskStatusRtn) {
        return new TimerTask() {
            @Override
            public void run() {
                log.info("executionPhase taskStatusRtn=>{}", JSON.toJSONString(taskStatusRtn));
                String result = StringUtils.EMPTY;
                for (int i = 0; i < WcsProperties.ATTEMPT_NUM_3; i++) {
                    try {
                        result = HttpClientSpring.sendPostRequest(WmsIpPortUtil.getUrl(SystemInit.getUrlByName("executionPhaseAsync")), JSON.toJSONString(taskStatusRtn));
                        if (StringUtils.isNotBlank(result)) {
                            break;
                        }
                    } catch (Exception e) {
                        log.info("executionPhase 接口异常", e);
                    }
                }
                TaskDB taskDB = taskDBService.queryTaskInfoByWMSId(taskStatusRtn.getTaskId());
                TaskDetailDB taskDetailDB = null;
                if (taskStatusRtn.getTaskStatus() == WmsTaskStatus.FINISH.getProgressNum()) {
                    taskDetailDB = taskDetailService.getTaskDetail(taskDB.getTaskId(), DetailProcess.TO_WMS_COMMIT, null,
                            null, taskDB.getEndNodeStr(), PrecessStatus.CONDUCT, null, PrecessOperation.COMMIT_WMS.getValue().toString());
                }
                log.info("executionPhase return data:{}", result);
                if (StringUtils.isBlank(result)) {
                    if (taskDetailDB != null) {
                        taskDetailDB.setStatus(PrecessStatus.EXCEPTION.getValue());
                        taskDetailDB.setDeviceInfo("接口异常");
                        taskDetailService.updateById(taskDetailDB);
                    }
                    createInterFaceLog(JSON.toJSONString(taskStatusRtn), result, "接口通讯异常！");
                    return;
                }
                try {
                    WmsResponses wmsResponses = JSON.parseObject(result, WmsResponses.class);
                    Integer returnStatus = wmsResponses.getReturnStatus();
                    Date msgTime = wmsResponses.getMsgTime();
                    String returnInfoFromWms = wmsResponses.getReturnInfo();
                    if (returnStatus == WcsProperties.SUCCESS) {
                        log.info("任务编号:" + taskStatusRtn.getTaskId() + " 任务状态：" + taskStatusRtn.getTaskStatus()
                                + " 的任务上报成功！ 时间-->" + msgTime);
                        if (taskStatusRtn.getTaskStatus() == WmsTaskStatus.FINISH.getProgressNum()) {
                            taskDBService.updateTaskStatus(taskDB, TaskStatus.COMMITTED);
                            nodeDBService.updateNodeDBByTask(taskDB);
                            taskDetailService.updateTaskDetailCompleteTime(taskDetailDB);
                            log.info("任务编号:" + taskStatusRtn.getTaskId() + "的任务上报成功，修改对应货位状态");
                        }
                        createInterFaceLog(JSON.toJSONString(taskStatusRtn), result, null);
                    } else if (returnStatus == WcsProperties.FAIL) {
                        log.error("任务编号:" + taskStatusRtn.getTaskId() + " 任务状态：" + taskStatusRtn.getTaskStatus()
                                + " 的任务上报失败！原因-->" + returnInfoFromWms + " 时间-->"
                                + msgTime);
                        if (taskDetailDB != null) {
                            taskDetailDB.setStatus(PrecessStatus.EXCEPTION.getValue());
                            taskDetailService.updateById(taskDetailDB);
                        }
                        taskDB.setRemark("500");
                        taskDBService.updateById(taskDB);
                        createInterFaceLog(JSON.toJSONString(taskStatusRtn), result, result);
                    } else {
                        log.error("returnStatus状态码不存在！");
                        if (taskDetailDB != null) {
                            taskDetailDB.setStatus(PrecessStatus.EXCEPTION.getValue());
                            taskDetailDB.setDeviceInfo("returnStatus状态码不存在！");
                            taskDetailService.updateById(taskDetailDB);
                        }
                        createInterFaceLog(JSON.toJSONString(taskStatusRtn), result, result);
                    }
                } catch (Exception e) {
                    log.error("任务执行状态上报接口解析返回值出现异常！{}", e.getMessage(), e);
                    if (taskDetailDB != null) {
                        taskDetailDB.setStatus(PrecessStatus.EXCEPTION.getValue());
                        taskDetailDB.setDeviceInfo("任务执行状态上报接口解析返回值出现异常");
                        taskDetailService.updateById(taskDetailDB);
                    }
                    createInterFaceLog(JSON.toJSONString(taskStatusRtn), result, e.getMessage());
                }
            }
        };
    }

    /**
     * 创建交互日志
     *
     * @param interfaceParamsIn  传入日志
     * @param interfaceParamsRet 返回日志
     * @param eMessage           异常信息
     */
    private void createInterFaceLog(String interfaceParamsIn, String interfaceParamsRet, String eMessage) {

        // *========数据库日志=========*//
        InterfaceLogDB interfaceLogDB = new InterfaceLogDB();
        interfaceLogDB.setStatus(BusinessStatus.SUCCESS.ordinal());
        // 返回参数
        interfaceLogDB.setInterfaceParamsRet(JSON.toJSONString(interfaceParamsRet));

        if (eMessage != null) {
            interfaceLogDB.setStatus(BusinessStatus.FAIL.ordinal());
            interfaceLogDB.setInterfaceParamsRet(StringUtils.substring(eMessage, 0, 2000));
        }
        //设置操作时间
        interfaceLogDB.setSendTime(new Date());


        interfaceLogDB.setInterfaceMethodDes("上报WMS日志");

        interfaceLogDB.setInterfaceParamsIn(StringUtils.substring(interfaceParamsIn, 0, 2000));

        // 保存数据库
        AsyncManager.me().execute(AsyncFactory.recordInterfaceOper(interfaceLogDB));
    }
}
